﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace Perm.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Greens
    {
        string selectMSSQL = "", String = "",
               error = null;
        double startX, startY,
               X, Y, kooficientMIN = 4.0, kooficientMAX = 1000.0;
        int id = 0;

        SqlConnection conMSSQL;
        SqlDataReader readerMSSQL;
        SqlCommand commandMSSQL;

        DateTime thisDate = DateTime.Now.ToUniversalTime().AddHours(6);

        List<Green> greenList = new List<Green>();
        Green green = new Green();
        GreenIn greenIn = new GreenIn();
        
        int i = 0;

        [OperationContract]
        public List<Green> DoWork(string city)
        {
            string connectionStringMSSQL = WebConfigurationManager.ConnectionStrings["MSSQL"].ConnectionString;

            try
            {
                conMSSQL = new SqlConnection(connectionStringMSSQL);
                conMSSQL.Open();
            }
            catch { error += " Невозможно подключиться к базе данных. MS SQL (LoadRoads)"; }

            switch (city)
            {
                case "perm":
                    {
                        //Запрос на зелень
                        selectMSSQL = "SELECT [NO], x, y, [INDEX], XCOORD, YCOORD FROM GREEN_PERM ORDER BY NO, [INDEX]";
                        break;
                    }
                case "ekb":
                    {
                        selectMSSQL = "SELECT [NO], x, y, [INDEX], XCOORD, YCOORD FROM GREEN_EKB ORDER BY NO, [INDEX]";
                        break;
                    }
                case "permkray":
                    {
                        selectMSSQL = "SELECT [NO], x, y, [INDEX], XCOORD, YCOORD FROM GREEN_PERMKRAY ORDER BY NO, [INDEX]";
                        break;
                    }
            }
            try
            {
                commandMSSQL = new SqlCommand(selectMSSQL, conMSSQL);
                readerMSSQL = commandMSSQL.ExecuteReader();
            }
            catch { error += "Невозможно считать данный из базы. MSSQL. "; }
                        
            string no = "";
            readerMSSQL.Read();
            startClass();
            while (readerMSSQL.Read())
            {
                if (readerMSSQL[3].ToString() != "1")
                {
                    addNoXY();
                    while (readerMSSQL.Read())
                    {
                        if (readerMSSQL.GetInt32(0) != green.id)
                        {
                            no = readerMSSQL[3].ToString();
                            greenList.Add(green); startClass();
                            break;
                        }
                        else
                        {
                            if (readerMSSQL[3].ToString() != green.no.Split(';')[green.no.Split(';').Length - 2])
                            {
                                addNoXY();
                            }
                            else i++;
                        }
                    }
                }
                else i++;                
            }
            #region old
            /*
            

            readerMSSQL.Read();
        m1:
            Green green = new Green();
            id = readerMSSQL.GetInt32(0);

            startX = Math.Round(readerMSSQL.GetDouble(1), 2);
            startY = Math.Round(readerMSSQL.GetDouble(2), 2);

            green.id = id;            
            green.X += startX + ";";
            green.Y += startY + ";";

            if ((Math.Abs(startX - X) > kooficientMIN || Math.Abs(startY - Y) > kooficientMIN))
            {
                X = Math.Round(readerMSSQL.GetDouble(4), 2);
                Y = Math.Round(readerMSSQL.GetDouble(5), 2);
                green.no += readerMSSQL.GetInt32(3) + ";";
                green.X += X + ";";
                green.Y += Y + ";";
            }

            while (readerMSSQL.Read())
            {
                if (readerMSSQL.GetInt32(0) == id)
                {
                    green.no += readerMSSQL.GetInt32(3) + ";";

                    double raznicaX = Math.Abs(Math.Round(readerMSSQL.GetDouble(4), 2) - X);
                    double razniczY = Math.Abs(Math.Round(readerMSSQL.GetDouble(5), 2) - Y);
                    if ((raznicaX > kooficientMIN || razniczY > kooficientMIN))
                    {
                        X = Math.Round(readerMSSQL.GetDouble(4), 2);
                        Y = Math.Round(readerMSSQL.GetDouble(5), 2);
                        green.X += X + ";";
                        green.Y += Y + ";";
                    }
                }
                else
                {
                    greenList.Add(green);
                    goto m1;
                }
            }
            */
#endregion
            return greenList;
        }
        /// <summary>
        /// Добавляем класс и записываем в него нулевую и первую точку
        /// </summary>
        void startClass()
        {
            green = new Green();
            green.id = readerMSSQL.GetInt32(0);
            green.no += readerMSSQL[3].ToString() + ";";
            green.X = readerMSSQL[1].ToString() + ";" + readerMSSQL[4].ToString() + ";";
            green.Y = readerMSSQL[2].ToString() + ";" + readerMSSQL[5].ToString() + ";";
        }
        /// <summary>
        /// Добавляем класс и записываем в него нулевую и первую точку
        /// </summary>
        void startClassIn()
        {
            greenIn = new GreenIn();
            greenIn.id = readerMSSQL[0].ToString() + "." + i;
            greenIn.no += readerMSSQL[3].ToString() + ";";
            greenIn.X = readerMSSQL[1].ToString() + ";" + readerMSSQL[4].ToString() + ";";
            greenIn.Y = readerMSSQL[2].ToString() + ";" + readerMSSQL[5].ToString() + ";";
        }
        /// <summary>
        /// Добавление точки и её номера в класс.
        /// </summary>
        void addNoXY()
        {
            green.no += readerMSSQL[3].ToString() + ";";
            green.X += readerMSSQL[4].ToString() + ";";
            green.Y += readerMSSQL[5].ToString() + ";";
        }
        [DataContract]
        public class Green
        {
            [DataMember]
            public int id = 0;
            [DataMember]
            public string no = "0;";
            [DataMember]
            public string X = "";
            [DataMember]
            public string Y = "";
            [DataMember]
            public List<Green> greenInList = new List<Green>();
        }
        public class GreenIn
        {
            [DataMember]
            public string id = "";
            [DataMember]
            public string no = "0;";
            [DataMember]
            public string X = "";
            [DataMember]
            public string Y = "";
        }
        // Add more operations here and mark them with [OperationContract]
    }
}
